package server;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

class TCPServer {

	public static void main(String argv[]) throws Exception {

		ServerSocket welcomeSocket = new ServerSocket(6789);
		System.out.println(welcomeSocket.getLocalSocketAddress());
		while (true) {
			try {
				Socket socket = welcomeSocket.accept();
				new ConnectionHandler(socket);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}

class ConnectionHandler implements Runnable {
	Socket socket;
	public static ArrayList<ClientSocket> clientList = new ArrayList<ClientSocket>();
	public static ArrayList<Output> outputList = new ArrayList<Output>();

	public ConnectionHandler(Socket socket) {
		this.socket = socket;
		Thread thread = new Thread(this);
		thread.start();
	}

	public void run() {
		String clientSentence = null;
		String capitalizedSentence = null;
String user=null;
		boolean connected = false;
		DataOutputStream outToClient = null;
		BufferedReader inFromClient = null;
		while (!connected) {

			try {
				inFromClient = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				outToClient = new DataOutputStream(socket.getOutputStream());
				user = inFromClient.readLine();
				ClientSocket c = new ClientSocket();
				c.setSocket(socket);
				c.setUser(user);
				clientList.add(c);

				Output out = new Output();
				out.setUser(user);
				out.setOutput(outToClient);
				out.setSocket(socket);
				outputList.add(out);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println("Received: " + user);
			connected = true;
		}
		while (connected) {
			DataOutputStream writeData=null;
			Output output;
			try {
				clientSentence = inFromClient.readLine();
				output = verifyOutput(clientSentence);
				if(output==null) output=verifyOutput(user);
				writeData=output.getOutput();
				clientSentence = inFromClient.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Received: " + clientSentence);
			capitalizedSentence = clientSentence.toUpperCase() + '\n';
			try {
			
				writeData.writeBytes(capitalizedSentence);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			connected = true;
		}

	}

	private Output verifyOutput(String clientSentence) {
	for(Output out:outputList)
		if(out.getUser().equals(clientSentence)) return out;
		return null;
	}
}
